package it.antonio.ilpizze.db.core;

import java.util.HashMap;
import java.util.Map;

import it.antonio.ilpizze.db.Cache;
import it.antonio.ilpizze.db.Caches;
import it.antonio.ilpizze.db.DbException;
import it.antonio.ilpizze.db.cache.CacheDelegate;

public class CachesProvider implements Caches {
	
	private TransactionManager txManager;
	private StatusManager statusManager;
	private LockManager lockManager;
	
	private Map<String, TransactionalCache> caches = new HashMap<String, TransactionalCache>();
	
	public CachesProvider(TransactionManager txManager, StatusManager statusManager, LockManager lockManager) {
		this.txManager = txManager;
		this.statusManager = statusManager;
		this.lockManager = lockManager;
	}

	@Override
	public Cache register(String name, CacheDelegate delegate) {
		statusManager.checkStatus(Status.OPEN);
		lockManager.checkMultiThreadingWrite();
		TransactionalCache cache = new TransactionalCache(delegate, txManager, statusManager);
		caches.put(name, cache);
		
		return cache;
	}

	@Override
	public Cache get(String name) {
		statusManager.checkStatus(Status.OPEN);
		lockManager.checkMultiThreadingRead();
		Cache cache = caches.get(name);
		if(cache == null) throw new DbException("No cache registered with name: " + name);
		
		return cache;
		
	}

	public void begin() {
		for(TransactionalCache c: caches.values()){
			c.begin();
		}
	}
	
	public void rollback() {
		for(TransactionalCache c: caches.values()){
			c.rollback();
		}
	}
	
	public void commit() {
		for(TransactionalCache c: caches.values()){
			c.commit();
		}
	}
	
}
